package com.llh.controller.processdata;

import com.llh.bean.FinalData;
import com.llh.bean.MiddleData;
import com.llh.controller.http.TradeCal;
import com.llh.controller.processdata.computVo.Daily_hz;
import com.llh.controller.processdata.computVo.PrimaryKey;
import com.llh.mapper.*;
import com.llh.util.SqlSessionUtil;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

public class ComputeDaily {
    static Logger logger = LogManager.getLogger(ComputeDaily.class.getName());

    public static Map<PrimaryKey, List<Daily_hz>> computOpenDay() {
        //所有的业务主键
        List<PrimaryKey> primaryKeyList = null;
        SqlSession sqlSession = null;
        try {
            sqlSession = SqlSessionUtil.getSqlSesion();
            //拿基础表中所有的
//            StockBaseMapper mapper = sqlSession.getMapper(StockBaseMapper.class);
//            primaryKeyList = mapper.findAllKey();
            //从final_data_2表中拿过滤后的主键
            FinalDataMapper mapper = sqlSession.getMapper(FinalDataMapper.class);
            primaryKeyList = mapper.findAllPk();

            logger.info("获取主键数据结束");

        } finally {
            sqlSession.close();
        }
        //存放每只股票对应的中间数据
        Map<PrimaryKey, MiddleData> pk_md = new HashMap<>();
        List<MiddleData> list = null;
        try {
            sqlSession = SqlSessionUtil.getSqlSesion();
            MiddleDataMapper mapper = sqlSession.getMapper(MiddleDataMapper.class);
            list = mapper.selectAll();
            logger.info("获取中间表数据结束");
        } finally {
            sqlSession.close();
        }
        for (MiddleData middleData : list) {
            PrimaryKey primaryKey = new PrimaryKey();
            primaryKey.setTs_code(middleData.getS_code());
            primaryKey.setOpen_day(middleData.getOpen_day());
            pk_md.put(primaryKey, middleData);
        }
        //查询每只股票预计应该有的151条记录对应的时间列表
        Map<PrimaryKey, List<Date>> pk_days = new HashMap<>();
        Set<PrimaryKey> primaryKeys = pk_md.keySet();
        int num = 0;
        for (PrimaryKey primaryKey : primaryKeys) {
            num++;
            MiddleData middleData = pk_md.get(primaryKey);
            //到交易日历表中取查对应电的数据
            sqlSession = SqlSessionUtil.getSqlSesion();
            OpenDayMapper mapper = sqlSession.getMapper(OpenDayMapper.class);
            List<Date> days = mapper.findDays(middleData);
            sqlSession.close();
            pk_days.put(primaryKey, days);
            logger.info("查询一天记录的时间里列表结束:"+num);
        }
        logger.info("查询每只股票预计应该有的151条记录对应的时间列表结束");
        //查询daily表中主键所有的涨跌额-hz300
        Map<PrimaryKey, List<Daily_hz>> daily_hz_map = new HashMap<>();
        int num2 = 0;
        for (PrimaryKey primaryKey : primaryKeys) {
            num2++;
            sqlSession = SqlSessionUtil.getSqlSesion();
            DailyMapper mapper = sqlSession.getMapper(DailyMapper.class);
            List<Daily_hz> hz = mapper.findHz(primaryKey);
            sqlSession.close();
            daily_hz_map.put(primaryKey, hz);
            logger.info("查询一天记录的涨跌幅数据结束:"+num2);
        }
            logger.info("查询daily表中主键所有的涨跌额-hz300结束");
        //对比并编排数据(每个组件151个数据),使用含有股票名的pk(即最终要到到表中的股票记录)
        Map<PrimaryKey, List<Daily_hz>> newDaily_hz_map = new HashMap<>();
        for (PrimaryKey primaryKey : primaryKeyList) {
            //对应预期的日期列表
            List<Date> dates = pk_days.get(primaryKey);
            //对应的日交易数据
            List<Daily_hz> daily_hzs = daily_hz_map.get(primaryKey);
            //按照预期的日期列表,组织性的日期和沪深300涨幅差的列表对象
            List<Daily_hz> newDaily_hzs = new ArrayList<>();
            for (Date date : dates) {
                Daily_hz daily_hz = new Daily_hz();
                daily_hz.setTrade_date(date);
                //是佛有匹配的数据的标识
                boolean flag = false;
                for (Daily_hz hz : daily_hzs) {
                    Date trade_date = hz.getTrade_date();
                    if (trade_date.equals(date)) {
                        daily_hz.setData(hz.getData());
                        flag = true;
                        break;
                    }
                }
                //如果没有的对应的值则设置为空
                if (!flag) {
                    daily_hz.setData(null);
                }
                newDaily_hzs.add(daily_hz);
            }
            //给最后的结果按照日期升序排序
            List<Daily_hz> sortedcollect = newDaily_hzs.stream().sorted(Comparator.comparing(Daily_hz::getTrade_date)).collect(Collectors.toList());
            //添加一个数据
            newDaily_hz_map.put(primaryKey, sortedcollect);
        }
        logger.info("数据组织结束,即将开始导表");
        return newDaily_hz_map;

    }

    public static void main(String[] args) throws Exception {
        Map<PrimaryKey, List<Daily_hz>> pkMap = computOpenDay();
//        System.out.print(primaryKeys+":");
//        System.out.println(pkMap.get(primaryKeys));
        File in = new File("C:\\Users\\llh\\Desktop\\每日涨幅表头导表.xlsx");
//        File out = new File("C:\\Users\\llh\\Desktop\\每日涨幅数据.xlsx");
                File out = new File("C:\\Users\\llh\\Desktop\\每日涨幅数据顺序验证.xlsx");

        writeExcel(in,out,1,pkMap);

    }

    //创建表头
    public static void creatExcel() throws Exception {
        XSSFWorkbook workbook1 = new XSSFWorkbook();
        SXSSFWorkbook sxssfWorkbook = new SXSSFWorkbook(workbook1, 100);
        SXSSFSheet sheet = sxssfWorkbook.createSheet("日行情");
        SXSSFRow row = sheet.createRow(0);
        SXSSFCell cell0_0 = row.createCell(0);
        cell0_0.setCellValue("股票代码");
        SXSSFCell cell0_1 = row.createCell(1);
        cell0_1.setCellValue("名称");
        SXSSFCell cell0_2 = row.createCell(2);
        cell0_2.setCellValue("解禁日T");
        for (int i = 1; i <= 151; i++) {
            SXSSFCell cell = row.createCell(2 + i);
            if (i != 121) {
                cell.setCellValue("T" + (i - 121));
            } else {
                cell.setCellValue("T");
            }
        }
        FileOutputStream fileOutputStream = new FileOutputStream(new File("C:\\Users\\llh\\Desktop\\每日涨幅表头导表.xlsx"));
        sxssfWorkbook.write(fileOutputStream);
        fileOutputStream.flush();
        fileOutputStream.close();
        sxssfWorkbook.close();
        System.out.println("结束");
    }

    //写数据
    public static void writeExcel(File in, File out, int startRow, Map<PrimaryKey, List<Daily_hz>> dataMap) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        FileInputStream fileInputStream = null;
        XSSFWorkbook workbook1 = null;
        SXSSFWorkbook sxssfWorkbook = null;
        FileOutputStream fileOutputStream = null;
        try {
            fileInputStream = new FileInputStream(in);
            workbook1 = new XSSFWorkbook(fileInputStream);
            sxssfWorkbook = new SXSSFWorkbook(workbook1, 100);
            SXSSFSheet sheet = sxssfWorkbook.getSheetAt(0);

            Set<PrimaryKey> primaryKeys = dataMap.keySet();
            for (PrimaryKey primaryKey : primaryKeys) {
                SXSSFRow row = sheet.createRow(startRow);
                SXSSFCell cell0_0 = row.createCell(0);
                cell0_0.setCellValue(primaryKey.getTs_code());
                SXSSFCell cell0_1 = row.createCell(1);
                cell0_1.setCellValue(primaryKey.getName());
                SXSSFCell cell0_2 = row.createCell(2);
                cell0_2.setCellValue(primaryKey.getOpen_day());
                List<Daily_hz> daily_hzs = dataMap.get(primaryKey);
                for (int i = 0; i < daily_hzs.size(); i++) {
                    SXSSFCell cell = row.createCell(3 + i);
                    //导真实数据
                    Double data = daily_hzs.get(i).getData();
                    if(data==null){
                        cell.setCellValue("");
                    }else{
//                        cell.setCellValue(daily_hzs.get(i).getData());
                        cell.setCellValue(new BigDecimal(data.toString()).setScale(4, BigDecimal.ROUND_HALF_UP).toString());
                    }
                    //导的是日期,验证逻辑是否正确的
             /*       Date trade_date = daily_hzs.get(i).getTrade_date();
                    cell.setCellValue(format.format(trade_date));*/

                }
                System.out.println("插入第" + startRow + "行数据完成");
                startRow++;
            }
            fileOutputStream = new FileOutputStream(out);
            sxssfWorkbook.write(fileOutputStream);
            fileOutputStream.flush();


        } finally {
            fileInputStream.close();
            fileOutputStream.close();
            sxssfWorkbook.close();
        }
    }

}
